//
//  StaffSelectImageView.swift
//  Employee
//
//  Created by tancheng on 2018/6/21.
//  Copyright © 2018年 remotevillage. All rights reserved.
//

import UIKit
import Photos

class StaffSelectImageView: UIView, UICollectionViewDelegate, UICollectionViewDataSource,PhotoPickerDelegate {

    //static let height = (UIScreen.width - 90) / 4
    var isSelect = true //是否可以选择图片
    
    var margin:CGFloat = 30
    
    var collectionView: UICollectionView!
    
    var assets:[PHAsset] = [] {
        didSet {
            collectionView.reloadData()
        }
    }
    
    var files: [NewImageModel] = [] {
        didSet {
            collectionView.reloadData()
            
            runInBackground {
                for (_, item) in self.files.enumerated() {
                    
                    if let data = try? Data.init(contentsOf: URL(string: item.thumbImageURL)!) {
                         let image = UIImage.init(data:data)
                         let model = SJImageModel.init(thumb: nil, thumb: image, original: item.accessUrl)
                        
                        self.browseImages.append(model)
                        
                    }
                }
                
                runOnMainThread {
                    self.collectionView.reloadData()
                }
                
            }
            
            

        }
    }
    
    var browseImages: [SJImageModel] = []
    
    
    
    fileprivate var assetIdentifier = ""
    
    var maxCount = 4
    
    weak var targetVC: UIViewController?
    
    fileprivate var selectImageV: SelectImagePopV = SelectImagePopV(frame: UIScreen.main.bounds)
    
    //
    var deleteImg:((Int)->())?
    var selectedImg:(([PHAsset])->())?
    //
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setupUI() {
        
        let flow = UICollectionViewFlowLayout()
        let width = (UIScreen.width - 2*margin - 30) / 4
        flow.itemSize = CGSize(width: width, height: width)
        flow.minimumInteritemSpacing = 10
        
        collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flow)
        collectionView.backgroundColor = UIColor.clear
        collectionView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 10)
        addSubview(collectionView)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(ImageSelectCell.self, forCellWithReuseIdentifier: ImageSelectCell.identifier)
        collectionView.register(ChooseImageCell.self, forCellWithReuseIdentifier: ChooseImageCell.identifier)
        collectionView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview()
            make.height.equalTo(width+10)
        }
        
        //
        selectImageV.takePhotoClosure = {[unowned self] in
            self.takePhoto()
        }
        
        selectImageV.selectClosure = { [unowned self] in
            
        let photoPicker = PhotoPicker(selectedCount: self.assets.count, maxCount: 4, delegate: self)
        self.targetVC?.navigationController?.pushViewController(photoPicker, animated: true)
        }
        
    }
    
    fileprivate func takePhoto() {
        
        if assets.count >= 4 {
            SJHint.show("你已经选择了四张啦")
            return
        }
        
        
       
            if GlobalConfig.isAuthorizationVideo() {
                let imagePicker = UIImagePickerController()
                imagePicker.delegate = self
                imagePicker.allowsEditing = true
                imagePicker.sourceType = .camera
                self.targetVC?.present(imagePicker, animated: true, completion: nil)
        }
        
        
        
    }
    
    //MARK:UICollectionViewDataSource
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return isSelect ? (assets.count < 4 ? assets.count + 1 : 4) : files.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        // 数量小于4,增加cell才会出现
        if indexPath.row == assets.count && isSelect {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ChooseImageCell.identifier, for: indexPath) as! ChooseImageCell
            
            cell.addPhotoClosure = { [weak self] in
                SJApp.endEdit()
                self?.selectImageV.show(in: SJApp.keyWindow)
            }
            
            return cell
        }
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageSelectCell.identifier, for: indexPath) as! ImageSelectCell
        
        cell.isHideDeleteButton = !isSelect
        cell.index = indexPath.row
        
        if isSelect {
            cell.asset = assets[indexPath.row]
        }else {
            cell.imageName = files[indexPath.row].thumbImageURL
            
            if browseImages.count > indexPath.row && browseImages[indexPath.row].thumbView == nil {
                browseImages[indexPath.row].thumbView = cell.imageV
            }
            
        }
        
        
        cell.deleteClosure = { [weak self] (index) in
            self?.assets.remove(at: index)
            collectionView.reloadData()
            if let closure = self?.deleteImg {
                closure(index)
            }
        }
        
        
        return cell
    }
    
    //MARK: UICollectionViewDelegate
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //
        
        guard !isSelect else {
            //let browser = PhotoViewer(with: assets, enterIndex: indexPath.row)
            return
        }
        
      let browser =  ImageViewer(images: browseImages, presentingVC: targetVC!)
       browser.show(index: indexPath.row)
        
    }
    
    
    //
    func photoPickerDidFinishSelected(_ assets: [PHAsset]) {
        self.assets += assets
        if let closure = self.selectedImg {
            closure(self.assets)
        }
    }
    
}

extension StaffSelectImageView: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
            return
        }
        
        
            PHPhotoLibrary.shared().performChanges({
                
                let request = PHAssetChangeRequest.creationRequestForAsset(from: image)
                self.assetIdentifier = request.placeholderForCreatedAsset?.localIdentifier ?? ""
                
            }) { (finish, error) in
                
                
                    
                    if nil != error {
                        runOnMainThread {
                            SJHint.show("获取照片失败, 请重新拍摄")
                            picker.dismiss(animated: true) { }
                        }
                        return
                    }
                    else {
                        
                        
                        
                        let tempAssets = PHAsset.fetchAssets(withLocalIdentifiers: [self.assetIdentifier], options: nil)
                        
                        guard let asset = tempAssets.firstObject else {
                            runOnMainThread {
                                SJHint.show("获取照片失败, 请重新拍摄")
                                picker.dismiss(animated: true) { }
                            }
                        
                            return
                        }
                        
                        runOnMainThread({
                            self.assets.append(asset)
                            self.selectedImg?(self.assets)
                            picker.dismiss(animated: true) { }
                        })
                        
                    }
                    
        }
    
}
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        runOnMainThread({
            picker.dismiss(animated: true) {
                
            }
        })
    }
    
}



